package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-01-05 19:04
 **/
public class LeetCode213 {

    public int rob(int[] nums) {
        int n = nums.length;
        if (n == 1) {
            return nums[0];
        } else if (n == 2) {
            return Math.max(nums[0], nums[1]);
        }

        //由于是个环,所以有两种情况,拿头不拿尾和拿尾不拿头,取两者中的最大值
        return Math.max(robRange(nums, 0, n - 2), robRange(nums, 1, n - 1));
    }

    int robRange(int[] nums, int start, int end) {
        int a = nums[start];
        int b = Math.max(a, nums[start + 1]);
        for (int i = start + 2; i <= end; ++i) {
            int c = b;
            b = Math.max(b, a + nums[i]);
            a = c;
        }

        return b;
    }

}
